package com.seeyon.apps.extracontract.thread;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.seeyon.apps.extracontract.util.FormUtils;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.filemanager.dao.AttachmentDAO;
import com.seeyon.ctp.common.po.filemanager.Attachment;

public class BackThread extends Thread{
	
	private final static Log log = LogFactory.getLog(BackThread.class);
	
	private FormApi4Cap4 formApi4Cap4 = (FormApi4Cap4) AppContext.getBean("formApi4Cap4");
	private AttachmentDAO attachmentDAO = (AttachmentDAO) AppContext.getBean("attachmentDAO");
	
	@Override
	public void run() {
		try {
			BackThread.sleep(10000);
			// -- 10秒后进行数据回写	
			FormDataMasterBean resultBean = formApi4Cap4.getDataMasterBeanById(bean.getId(), formBean, null);
			FormUtils formUtils = new FormUtils(formBean, resultBean);
			
			Map<String, Attachment> map = updateMap.get(resultBean.getId());
			for(Map.Entry<String, Attachment> entry : map.entrySet()){
				String display = entry.getKey();
				String field = formUtils.getField(display);
				Attachment att = entry.getValue();
				attachmentDAO.save(att);
				resultBean.addFieldValue(field, att.getSubReference());
			}
				formApi4Cap4.saveOrUpdateFormData(resultBean, formBean.getId(), true);
		} catch (Exception e) {
			log.info("回写线程执行失败", e);
		}
	}
	
	
	// --- 基本数据引用注入
	private FormDataMasterBean bean; 				//--需要调整的数据表单
	private FormBean formBean;						//--表单定义表
	private Map<Long, Map<String, Attachment>> updateMap; //--需要更新的表单信息

	public FormDataMasterBean getBean() {
		return bean;
	}
	public void setBean(FormDataMasterBean bean) {
		this.bean = bean;
	}
	public FormBean getFormBean() {
		return formBean;
	}
	public void setFormBean(FormBean formBean) {
		this.formBean = formBean;
	}
	public Map<Long, Map<String, Attachment>> getUpdateMap() {
		return updateMap;
	}
	public void setUpdateMap(Map<Long, Map<String, Attachment>> updateMap) {
		this.updateMap = updateMap;
	}
	
}
